/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import Control.Control;
import Logic.DataBaseLink;
import Logic.Filtro;
import static Logic.Filtro.dateFormatString;
import Logic.Log;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Window;
import java.lang.Object;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author David-PC
 */
public class GUI_Log extends javax.swing.JFrame {
    
    static class DateRenderer extends DefaultTableCellRenderer {
        DateFormat formatter;
        public DateRenderer() { super(); }

        @Override
        public void setValue(Object value) {
            if (formatter==null) {
                formatter = new SimpleDateFormat(dateFormatString);
            }
            setText((value == null) ? "" : formatter.format(value));
        }
    }

    /**
     * Creates new form GUI_Log
     */
    DateFormat dateFormat = new SimpleDateFormat(Filtro.dateFormatString);
    
    public GUI_Log() {
        initComponents();
        fechaDesde.setEditor(new JSpinner.DateEditor(fechaDesde, Filtro.dateFormatString));
        fechaHasta.setEditor(new JSpinner.DateEditor(fechaHasta, Filtro.dateFormatString));
        centreWindow(this);
        loadTable();
        loadActionCB();
        loadServerCB();
        

    }
    public void loadServerCB(){
        
        serverCB.removeAllItems();
        
        Control control = Control.getInstance();
        //control.load_links();
        ArrayList<DataBaseLink> list=control.getDblinks();
        
        serverCB.insertItemAt("All", 0);
        for(int i=0;i<list.size();i++){
            serverCB.insertItemAt(list.get(i).getName(), i+1);
        }
        serverCB.insertItemAt("LOCAL", list.size()+1);
        serverCB.setSelectedIndex(0);
    }
    public void loadActionCB(){
        
        actionCB.removeAllItems();

        actionCB.insertItemAt("All", 0);
        actionCB.insertItemAt(Log.CONNECTION, 1);
        actionCB.insertItemAt(Log.NEW_CLASIFICATION, 2);
        actionCB.insertItemAt(Log.UPDATE_CLASIFICATION, 3);
        actionCB.insertItemAt(Log.DELETE_CLASIFICATION, 4);
        actionCB.insertItemAt(Log.ASSIGN_PRIVILEGE, 5);
        actionCB.insertItemAt(Log.NEW_USER, 6);
        actionCB.insertItemAt(Log.DELETE_USER, 7);
        actionCB.insertItemAt(Log.ASSIGN_CLASSIFICATION, 8);
        actionCB.insertItemAt(Log.UNASSIGN_CLASSIFICATION, 9);
        actionCB.insertItemAt(Log.CREATE_RULE, 10);
        actionCB.insertItemAt(Log.AUDIT, 11);
        actionCB.insertItemAt(Log.ADD_SERVER, 12);
        actionCB.insertItemAt(Log.EDIT_SERVER, 13);
        actionCB.insertItemAt(Log.REMOVE_SERVER, 14);
        
        actionCB.setSelectedIndex(0);
    }
    
    public void clearTable(JTable jtable){
        while(jtable.getRowCount()>0){
            ((DefaultTableModel)jtable.getModel()).removeRow(0);
        }
    }
    
    public void loadTable(){
        clearTable(this.logTable);
        Control control = Control.getInstance();
        control.loadLogs();
        ArrayList<Log> logs =control.getLogs();
        
        
        for(int i=0;i<logs.size();i++){
            Log l = logs.get(i);
            String dateFormated = dateFormat.format(l.getDate());
            ((DefaultTableModel)this.logTable.getModel()).addRow(new Object[]{l.getDate(),l.getUser(),l.getServer(),l.getAction(),l.getDetails()});
        }
    }
    public static void centreWindow(Window frame) {
        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
        int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
        frame.setLocation(x, y);
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        filterPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        fechaDesde = new javax.swing.JSpinner();
        jLabel5 = new javax.swing.JLabel();
        fechaHasta = new javax.swing.JSpinner();
        jCheckBox1 = new javax.swing.JCheckBox();
        jLabel2 = new javax.swing.JLabel();
        serverCB = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        actionCB = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        byDetail = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        byUserTF = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        logTable = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Logs");

        filterPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Filter"));

        jLabel1.setText("By Date From:");

        fechaDesde.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.MINUTE));
        fechaDesde.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                fechaDesdeStateChanged(evt);
            }
        });

        jLabel5.setText("To:");

        fechaHasta.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.MINUTE));
        fechaHasta.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                fechaHastaStateChanged(evt);
            }
        });

        jCheckBox1.setText("All Dates");
        jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox1ActionPerformed(evt);
            }
        });

        jLabel2.setText("By Server: ");

        serverCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "All" }));
        serverCB.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                serverCBItemStateChanged(evt);
            }
        });

        jLabel3.setText("By Action:");

        actionCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "All" }));
        actionCB.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                actionCBItemStateChanged(evt);
            }
        });

        jLabel4.setText("By Detail: ");

        byDetail.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                byDetailKeyReleased(evt);
            }
        });

        jButton1.setText("Update");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel6.setText("By User: ");

        byUserTF.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                byUserTFKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout filterPanelLayout = new javax.swing.GroupLayout(filterPanel);
        filterPanel.setLayout(filterPanelLayout);
        filterPanelLayout.setHorizontalGroup(
            filterPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(filterPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(filterPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(filterPanelLayout.createSequentialGroup()
                        .addGroup(filterPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(filterPanelLayout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(serverCB, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(filterPanelLayout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(fechaDesde)))
                        .addGap(10, 10, 10)
                        .addGroup(filterPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(filterPanelLayout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(actionCB, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(filterPanelLayout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(fechaHasta, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(12, 12, 12)
                                .addComponent(jCheckBox1)))
                        .addGap(18, 18, 18)
                        .addGroup(filterPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel6))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(filterPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(byUserTF, javax.swing.GroupLayout.DEFAULT_SIZE, 218, Short.MAX_VALUE)
                            .addComponent(byDetail)))
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        filterPanelLayout.setVerticalGroup(
            filterPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(filterPanelLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(filterPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(serverCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(actionCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(byDetail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(filterPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(fechaDesde, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(fechaHasta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jCheckBox1)
                    .addComponent(jLabel6)
                    .addComponent(byUserTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1))
        );

        logTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Date", "User", "Server", "Action", "Details"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        logTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                logTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(logTable);
        logTable.getColumnModel().getColumn(0).setPreferredWidth(100);
        logTable.getColumnModel().getColumn(0).setCellRenderer(new DateRenderer());
        logTable.getColumnModel().getColumn(4).setPreferredWidth(300);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(filterPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(filterPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        loadTable();
        
        loadActionCB();
        loadServerCB();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void logTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_logTableMouseClicked
        if(evt.getClickCount()>=2){
            int columnSize = logTable.getModel().getColumnCount();
            String args[] = new String[columnSize];
            int index = logTable.getSelectedRow();
            args[0]= dateFormat.format(((Date)logTable.getModel().getValueAt(index,0)));
            for(int i=1;i<columnSize;i++){
                args[i] = (String)logTable.getValueAt(index, i);
            }
            
           GUI_LogView v = new GUI_LogView(args);
           v.setVisible(true);
        }
    }//GEN-LAST:event_logTableMouseClicked

    private void byUserTFKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_byUserTFKeyReleased
        String target = byUserTF.getText();  
        TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(logTable.getModel());
        logTable.setRowSorter(sorter);
        sorter.setRowFilter(RowFilter.regexFilter(target, 1));
    }//GEN-LAST:event_byUserTFKeyReleased

    private void byDetailKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_byDetailKeyReleased
        String target = byDetail.getText();  
        TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(logTable.getModel());
        logTable.setRowSorter(sorter);
        sorter.setRowFilter(RowFilter.regexFilter(target, 4));
    }//GEN-LAST:event_byDetailKeyReleased

    private void actionCBItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_actionCBItemStateChanged
        String target = (String)actionCB.getSelectedItem();
        if(target!=null&&!target.equals("All")){
            TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(logTable.getModel());
            logTable.setRowSorter(sorter);
            sorter.setRowFilter(RowFilter.regexFilter(target, 3));
        }
        if(target!=null&&target.equals("All")){
            TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(logTable.getModel());
            logTable.setRowSorter(sorter);
            sorter.setRowFilter(RowFilter.regexFilter("^", 3));
        }
        
    }//GEN-LAST:event_actionCBItemStateChanged

    private void serverCBItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_serverCBItemStateChanged
        String target = (String)serverCB.getSelectedItem();
        if(target!=null&&!target.equals("All")){
            TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(logTable.getModel());
            logTable.setRowSorter(sorter);
            sorter.setRowFilter(RowFilter.regexFilter(target, 2));
        }
        if(target!=null&&target.equals("All")){
            TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(logTable.getModel());
            logTable.setRowSorter(sorter);
            sorter.setRowFilter(RowFilter.regexFilter("^", 3));
        }
    }//GEN-LAST:event_serverCBItemStateChanged

    private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed
        if(jCheckBox1.isSelected()){
            TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(logTable.getModel());
            logTable.setRowSorter(sorter);
            sorter.setRowFilter(RowFilter.regexFilter("^", 0));
        }
    }//GEN-LAST:event_jCheckBox1ActionPerformed

    private void fechaDesdeStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_fechaDesdeStateChanged
        
        jCheckBox1.setSelected(false);
        
        Date target = (Date)fechaDesde.getValue();
        Date target2 = (Date)fechaHasta.getValue();
        TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(logTable.getModel());
        logTable.setRowSorter(sorter);
        
        ArrayList<RowFilter<Object,Object>> filters = new ArrayList<RowFilter<Object,Object>>(2);
        filters.add(RowFilter.dateFilter(RowFilter.ComparisonType.AFTER, target, 0));
        filters.add(RowFilter.dateFilter(RowFilter.ComparisonType.BEFORE, target2, 0));
        sorter.setRowFilter(RowFilter.andFilter(filters));
    }//GEN-LAST:event_fechaDesdeStateChanged

    private void fechaHastaStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_fechaHastaStateChanged
        jCheckBox1.setSelected(false);
        
        Date target = (Date)fechaDesde.getValue();
        Date target2 = (Date)fechaHasta.getValue();
        TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(logTable.getModel());
        logTable.setRowSorter(sorter);
        
        ArrayList<RowFilter<Object,Object>> filters = new ArrayList<RowFilter<Object,Object>>(2);
        filters.add(RowFilter.dateFilter(RowFilter.ComparisonType.AFTER, target, 0));
        filters.add(RowFilter.dateFilter(RowFilter.ComparisonType.BEFORE, target2, 0));
        sorter.setRowFilter(RowFilter.andFilter(filters));
    }//GEN-LAST:event_fechaHastaStateChanged


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox actionCB;
    private javax.swing.JTextField byDetail;
    private javax.swing.JTextField byUserTF;
    private javax.swing.JSpinner fechaDesde;
    private javax.swing.JSpinner fechaHasta;
    private javax.swing.JPanel filterPanel;
    private javax.swing.JButton jButton1;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable logTable;
    private javax.swing.JComboBox serverCB;
    // End of variables declaration//GEN-END:variables
}
